package com.itheima.tlias84.exception;

import ch.qos.logback.core.model.processor.ModelHandlerException;
import com.itheima.tlias84.utils.ResultUtil;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 应为我们无法只用try-catch捕获进入controller之前的异常，但是可以使用aop对controller进行调用之前的增强
 * 因此这个@RestControllerAdvice注解相当于环绕通知controller
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ArithmeticException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResultUtil handlerArithmeticException(ArithmeticException exception){
        return ResultUtil.fail(exception.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResultUtil handleMethodArgumentNotValidException(MethodArgumentNotValidException exception){
        String message = exception.getFieldError().getDefaultMessage();
        Object rejectedValue = exception.getFieldError().getRejectedValue();

        return ResultUtil.fail(message,rejectedValue);

    }
}
